package com.jlastu.znb.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.transition.Slide;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jlastu.znb.R;
import com.jlastu.znb.adapter.GoodsPhotoAdapter;
import com.jlastu.znb.contract.AddGoodsContract;
import com.jlastu.znb.entity.Goods;
import com.jlastu.znb.entity.Photo;
import com.jlastu.znb.presenter.AddGoodsPresenter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddGoodsActivity extends AppCompatActivity implements
        GoodsPhotoAdapter.OnPhotoListener, AddGoodsContract.IAddGoodsView, View.OnClickListener {

   private RecyclerView mPhotoRecyclerView;
   private EditText mGoodsNameEdit;
   private Button mSendButton;
   private ImageView mBack;
   private List<Photo> mPhotoList;
   private GoodsPhotoAdapter mGoodsPhotoAdapter;
   private ActivityResultLauncher mActivityResultLauncher;
   private AddGoodsContract.IAddGoodsPresenter mAddGoodsPresenter;
   private RelativeLayout mGoodsAddressLayout;
   private TextView mClassSelectTextView;
   private ImageView mPriceSelectImageView;
   private TextView mPriceSelectTextView;
   private TextView mAddressTextView;
   private TextView mTransactionRules;

   @SuppressLint("WrongViewCast")
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      getWindow().setEnterTransition(new Slide());
      setContentView(R.layout.activity_add_goods);
      mAddGoodsPresenter = new AddGoodsPresenter(this, this);
      mPhotoList = new ArrayList<>();
      mPhotoList.add(new Photo());
      mPhotoRecyclerView = findViewById(R.id.rv_goods_photo);
      mGoodsNameEdit = findViewById(R.id.et_goods_name);
      mSendButton = findViewById(R.id.goods_send);
      mSendButton.setOnClickListener(this);
      GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
      gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
      mPhotoRecyclerView.setLayoutManager(gridLayoutManager);
      mGoodsPhotoAdapter = new GoodsPhotoAdapter(mPhotoList);
      mGoodsPhotoAdapter.setPhotoListener(this);
      mPhotoRecyclerView.setAdapter(mGoodsPhotoAdapter);
      onActivityResult();
      mBack = findViewById(R.id.back);
      mBack.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            onBackPressed();
            finish();
         }
      });
      mClassSelectTextView = findViewById(R.id.class_select);
      mPriceSelectTextView = findViewById(R.id.price);
      mPriceSelectImageView = findViewById(R.id.price_select);
      mAddressTextView = findViewById(R.id.tv_goods_address_hint);

      // 设置分类选择点击事件
      mClassSelectTextView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showClassPicker();
         }
      });
      mPriceSelectImageView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showPricePicker();
         }
      });

      // 设置地址选择点击事件
      mGoodsAddressLayout = findViewById(R.id.goods_address);
      mGoodsAddressLayout.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showAddressPicker();
         }
      });
      mTransactionRules = findViewById(R.id.rules);
      mTransactionRules.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent intent = new Intent(AddGoodsActivity.this,TransactionRulesActivity.class);
            startActivity(intent);
         }
      });

   }

   @Override
   public void onAdd() {
      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);
      mActivityResultLauncher.launch(intent);
   }

   @Override
   public void onDelete(int position) {
      //暂时没用
   }

   private void onActivityResult() {
      mActivityResultLauncher = registerForActivityResult(
              new ActivityResultContracts.StartActivityForResult(),
              new ActivityResultCallback<ActivityResult>() {
                 @Override
                 public void onActivityResult(ActivityResult result) {
                    int resultCode = result.getResultCode();
                    if (resultCode == RESULT_OK) {
                       Intent data = result.getData();
                       Uri selectedImageUri = data.getData();
                       try {
                          // 使用图片URI进行处理，例如加载到ImageView中
                          Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                          Photo photo = new Photo();
                          photo.setBitmap(bitmap);
                          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                          Bitmap resized = Bitmap.createScaledBitmap(bitmap, (int)(bitmap.getWidth()*0.5), (int)(bitmap.getHeight()*0.5), true);
                          resized.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                          photo.setData(outputStream.toByteArray());
                          mGoodsPhotoAdapter.addPhoto(photo);
                       } catch (IOException e) {
                          e.printStackTrace();
                       }
                    }
                 }
              });
   }

   @Override
   public void showGoodsList(List<Goods> goodsList) {

   }
   @Override
   public void showClassPickerDialog() {
      showClassPicker(); // 实现新增的回调方法
   }

   @Override
   public void onClick(View v) {
      if (v.getId() == R.id.goods_send) {
         // 获取用户输入的数据
         String goodsName = mGoodsNameEdit.getText().toString();
         String priceNumericPart = ((EditText) findViewById(R.id.price_edit)).getText().toString(); // 获取价格的数字部分
         String priceUnit = mPriceSelectTextView.getText().toString(); // 获取价格的单位部分
         String address = mAddressTextView.getText().toString(); // 发货地址
         String category = mClassSelectTextView.getText().toString().trim();

         // 转换价格数字为double
         double price = 0.0;
         try {
            price = Double.parseDouble(priceNumericPart); // 转换为double
         } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的价格数字", Toast.LENGTH_SHORT).show();
            return; // 如果转换失败，返回不执行后续操作
         }

         // 确保所有输入都有效，然后创建Goods对象并设置属性
         if (!goodsName.isEmpty() && price > 0 && !address.isEmpty()) {
            Goods goods = new Goods();
            goods.setName(goodsName);
            goods.setPrice(price);
            // 价格单位设置为单位字符串
            goods.setUnit(priceUnit);
            goods.setMessage("这里是商品描述，可以是商品的特点、优势等");
            goods.setPhotoList(mGoodsPhotoAdapter.getPhotoList());
            goods.setAddress(address);
            goods.setCategory(category);
            // 保存商品到数据库
            mAddGoodsPresenter.saveGoods(goods);
            onBackPressed();
         } else {
            // 显示错误信息，提示用户输入完整
            Toast.makeText(this, "请填写完整的商品信息", Toast.LENGTH_SHORT).show();
         }
      }
   }
   private void showClassPicker() {
      // 创建 AlertDialog
      final AlertDialog.Builder builder = new AlertDialog.Builder(AddGoodsActivity.this);
      LayoutInflater inflater = getLayoutInflater();
      View dialogView = inflater.inflate(R.layout.goods_class_select, null); // 使用您的分类选择布局
      builder.setView(dialogView);
      final AlertDialog dialog = builder.create();

      final RadioGroup radioGroup = dialogView.findViewById(R.id.radio_group);
      TextView determineButton = dialogView.findViewById(R.id.determine);
      ImageView closeButton = dialogView.findViewById(R.id.close_button);

      // 初始化时禁用确定按钮
      determineButton.setEnabled(false);

      // RadioGroup 的监听器，用于检查是否选择了一个选项
      radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(RadioGroup group, int checkedId) {
            // 启用确定按钮
            determineButton.setEnabled(true);
            // 更新 mClassSelectTextView 文本
            String text = (String) ((RadioButton) group.findViewById(checkedId)).getText();
            mClassSelectTextView.setText(text);
            Log.d("TAG", "onCheckedChanged: "+text);
         }
      });

      // determineButton 的点击事件
      determineButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // 点击确定后的操作
            dialog.dismiss();
         }
      });

      // closeButton 的点击事件
      closeButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss();
         }
      });

      // 显示对话框
      dialog.show();
   }
   private void showPricePicker() {
      // 创建 AlertDialog
      final AlertDialog.Builder builder = new AlertDialog.Builder(AddGoodsActivity.this);
      LayoutInflater inflater = getLayoutInflater();
      View dialogView = inflater.inflate(R.layout.price_select, null); // 使用您的价格选择布局
      builder.setView(dialogView);
      final AlertDialog dialog = builder.create();

      // 获取 RadioGroup 和其他控件
      final RadioGroup radioGroup = dialogView.findViewById(R.id.radio_group);
      final TextView determineButton = dialogView.findViewById(R.id.determine);
      ImageView closeButton = dialogView.findViewById(R.id.close_button);
      final TextView priceTextView = findViewById(R.id.price); // 确保这个ID与您的布局文件中定义的相符

      // 为 RadioGroup 设置监听器，以便在选项变化时更新界面
      radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(RadioGroup group, int checkedId) {
            // 当选择变化时，获取选中的RadioButton的文本，并更新priceTextView
            RadioButton selectedRadioButton = radioGroup.findViewById(checkedId);
            priceTextView.setText(selectedRadioButton.getText());
         }
      });

      // 为关闭按钮设置点击事件
      closeButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss();
         }
      });

      // 为确定按钮设置点击事件
      determineButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // 点击确定后的操作，可以在这里添加其他逻辑，比如保存选中的单位
            dialog.dismiss();
         }
      });

      // 显示对话框
      dialog.show();
   }

   private void showAddressPicker() {
      // 假设这是从数据库或其他数据源获取的省市区数据
      Map<String, List<String>> provinceCityMap = new HashMap<>();
      Map<String, List<String>> cityDistrictMap = new HashMap<>();

      // 示例数据填充
      provinceCityMap.put("吉林省", Arrays.asList("长春市", "吉林市", "四平市"));
      provinceCityMap.put("云南省", Arrays.asList("昆明市", "曲靖市", "玉溪市"));

      // 假设每个城市下都有一些区域
      cityDistrictMap.put("长春市", Arrays.asList("南关区", "宽城区", "朝阳区"));
      cityDistrictMap.put("吉林市", Arrays.asList("昌邑区", "龙潭区", "船营区"));
      cityDistrictMap.put("昆明市", Arrays.asList("五华区", "盘龙区", "西山区"));
      cityDistrictMap.put("曲靖市", Arrays.asList("麒麟区", "沾益区", "马龙区"));

      final AlertDialog.Builder builder = new AlertDialog.Builder(AddGoodsActivity.this);
      LayoutInflater inflater = getLayoutInflater();
      View dialogView = inflater.inflate(R.layout.address_select, null);
      builder.setView(dialogView);
      final AlertDialog dialog = builder.create();

      // 初始化 Spinner
      final Spinner spinnerProvince = dialogView.findViewById(R.id.spinner_province);
      final Spinner spinnerCity = dialogView.findViewById(R.id.spinner_city);
      final Spinner spinnerDistrict = dialogView.findViewById(R.id.spinner_district);

      // 填充省份 Spinner
      ArrayAdapter<String> provincesAdapter = new ArrayAdapter<>(this,
              android.R.layout.simple_spinner_item, new ArrayList<>(provinceCityMap.keySet()));
      provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinnerProvince.setAdapter(provincesAdapter);

      // 省份 Spinner 监听器
      spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
         @Override
         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedProvince = parent.getItemAtPosition(position).toString();
            List<String> cities = provinceCityMap.get(selectedProvince);
            // 更新城市 Spinner
            ArrayAdapter<String> citiesAdapter = new ArrayAdapter<>(
                    AddGoodsActivity.this,
                    android.R.layout.simple_spinner_item, cities);
            citiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerCity.setAdapter(citiesAdapter);
            // 重置区域 Spinner
            spinnerDistrict.setAdapter(new ArrayAdapter<>(
                    AddGoodsActivity.this,
                    android.R.layout.simple_spinner_item, new ArrayList<>()));
         }

         @Override
         public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing
         }
      });

      // 填充城市 Spinner
      ArrayAdapter<String> citiesAdapter = new ArrayAdapter<>(this,
              android.R.layout.simple_spinner_item, new ArrayList<>(provinceCityMap.values().iterator().next()));
      citiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinnerCity.setAdapter(citiesAdapter);

      // 城市 Spinner 监听器
      spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
         @Override
         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedCity = parent.getItemAtPosition(position).toString();
            List<String> districts = cityDistrictMap.get(selectedCity);
            // 更新区域 Spinner
            ArrayAdapter<String> districtsAdapter = new ArrayAdapter<>(
                    AddGoodsActivity.this,
                    android.R.layout.simple_spinner_item, districts);
            districtsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerDistrict.setAdapter(districtsAdapter);
         }

         @Override
         public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing
         }
      });

      // 设置对话框按钮
      TextView determineButton = dialogView.findViewById(R.id.determine);
      determineButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
               // 获取选中的省市区
               String selectedProvince = spinnerProvince.getSelectedItem().toString();
               String selectedCity = spinnerCity.getSelectedItem().toString();
               String selectedDistrict = spinnerDistrict.getSelectedItem().toString();

               // 构建完整的地址字符串
               String fullAddress = selectedProvince + " " + selectedCity + " " + selectedDistrict;

               // 更新发货地址文本
               mAddressTextView.setText(fullAddress);

               // 关闭对话框
               dialog.dismiss();
         }
      });


      // 设置关闭按钮的点击事件
      ImageView closeButton = dialogView.findViewById(R.id.close_button);
      closeButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss(); // 关闭对话框
         }
      });
      // 显示对话框
      dialog.show();
   }

}